from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from django.contrib.auth.hashers import make_password, check_password

from .. import models

# Create your views here.

# 后台 - 首页
def index(request):
    return render(request,'myadmin/index.html')

# 后台 - 登陆
def adminlogin(request):
    if request.method == 'GET':
        return render(request,'myadmin/login.html')
    else:
        # 接收表单数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')

        # 检测验证码是否正确
        if request.session['verifycode'] != data['vcode'].upper() :
            return HttpResponse('<script>alert("验证码错误");location.href="/admin/login"</script>')

        # 检测账号是否存在
        try:
            # 根据用户名获取用户
            userobj = models.Users.objects.get(username=data['username'])
            # 检测密码是否正确
            if check_password(data['password'],userobj.password):
                # 账号密码都正确，进行会话控制
                request.session['AdminUser'] = {'id':userobj.id,'username':userobj.username,'face':userobj.face_url}
                return HttpResponse(f'<script>alert("登陆成功");location.href="/admin"</script>')
            else:
                return HttpResponse('<script>alert("账号或密码错误");location.href="/admin/login"</script>')
        except:
            return HttpResponse('<script>alert("账号或密码错误");location.href="/admin/login"</script>')


# 后台 - 退出登陆
def adminlogout(request):
    request.session['AdminUser'] = ''
    return HttpResponse('<script>alert("已退出登陆");location.href="/admin/login"</script>')


# 验证码
def verifycode(request):
    # 导入绘图模块，随机数模块，io模块
    import random
    import io
    from PIL import Image,ImageDraw,ImageFont
    # 定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20,100),random.randrange(20,100),255)
    width = 100
    height = 35
    # 创建画面对象
    im = Image.new('RGB',(width,height),bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的 point() 函数绘制噪点
    for i in range(0,100):
        xy = (random.randrange(0,width),random.randrange(0,height))
        fill = (random.randrange(0,255),255,random.randrange(0,255))
        draw.point(xy,fill=fill)
    # 定义验证码的备选值
    str1 = '1234567890QWERTYUIOPASDFGHJKLZXCVBNM0'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0,4):
        rand_str += str1[random.randrange(0,len(str1))]
    # 构造字体对象
    font = ImageFont.truetype('upcib.ttf',40)
    # 构造字体颜色
    fontcolor = (255,random.randrange(0,255),random.randrange(0,255))
    # 绘制4个字
    draw.text((10,6),rand_str[0],font=font,fill=fontcolor)
    draw.text((35,6),rand_str[1],font=font,fill=fontcolor)
    draw.text((55,6),rand_str[2],font=font,fill=fontcolor)
    draw.text((75,6),rand_str[3],font=font,fill=fontcolor)
    # 释放画笔
    del draw
    # 存入session，用于验证
    request.session['verifycode'] = rand_str
    # 内存文件操作
    buf = io.BytesIO()
    # 将图片保存在内存中，类型为png
    im.save(buf,'png')
    # 将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(),'image/png')













